package cn.fzkj.controller;

import cn.fzkj.common.ResultVO;
import cn.fzkj.utils.ExcelUtils;
import cn.fzkj.utils.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @DESCRIPTION: TODO
 * @AUTHOR: AnotherOne
 * @DATE: 2021/9/10 11:18
 */
@Controller
public class IndexController {

    @RequestMapping(value = {"/","/index.html"})
    public String index(){
        return "index";
    }

    @ResponseBody
    @RequestMapping(value = {"/users"})
    public String user(){
        return "index";
    }

    /**
     * 导出请求
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public ResultVO export(){
        // 先不处理传入的需要导出的字段，先全部导出
        return ResultVO.success(ExcelUtils.exportExcel("取个名字"));
    }

    /**
     * 通用下载请求
     * @param fileName 文件名称
     * @param delete 是否删除
     */
    @ResponseBody
    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public void download(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request){
        // 下载请求，通过输出流将文件写回客户端
        fileName = "test.xls";
        delete = true;
        try {
            // 验证fileName合法性
            if (!FileUtils.isValidFilename(fileName)){
                throw new Exception("文件名称非法");
            }
            String filePath = "F:/test.xls";
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, "test.xls"));
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete){
                FileUtils.deleteFile(filePath);
            }
        }catch (Exception e){
            System.out.println("文件下载失败");
            e.printStackTrace();
        }
    }

}
